package com.example.springboottestgit.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSONObject;
import com.example.springboottestgit.bean.vo.EconomicPolicyContent;
import com.example.springboottestgit.bean.vo.TestVO;
import com.example.springboottestgit.utils.FileUtil;
import com.example.springboottestgit.utils.HttpUtils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @description:
 * @author: ZZZ
 */
public class TestMain {
    static Map<String, List<TestVO>> map = new HashMap<>();

    public static void main(String[] args) {
        //生成问题
        //questionAll();

        //收集问题回答结果
        answerAll();
    }

    public static void answerAll() {
        int k = 0;
        Date now = new Date();
        // 定义格式化模式
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmm");
        // 格式化为字符串
        String nowDate = sdf.format(now);
        List<TestVO> excelList = readExcelData("C:\\Users\\user\\Desktop\\经济政策\\经济政策文件问题.xlsx");

        for (TestVO vo : excelList) {

            Map<String, String> params = new HashMap<>();
            params.put("question", vo.getQuestion());
            if (vo.getFileName() != null && vo.getFileName().length() > 5) {
                params.put("fileName", vo.getFileName().replace(".txt", ""));
            }

            System.out.println(k++);
            System.out.println(vo.getQuestion());
            String output = HttpUtils.post("http://127.0.0.1:8088/economic/policy/test", JSONObject.toJSONString(params));
            JSONObject data = JSONObject.parseObject(output).getJSONObject("data");
            String answer = data.getString("answer");
            vo.setAnswer(answer);
            System.out.println(output);
            System.out.println();

            String document = data.getString("document");
            vo.setDocument(document);
            if (vo.getType().equals("文件问题")) {
                String esMatch = data.getString("esMatch");
                vo.setEsMatch(esMatch);

                String vectorMatch = data.getString("vectorMatch");
                vo.setVectorMatch(vectorMatch);

                //文本记录
                String txtPath = String.format("C:\\Users\\user\\Desktop\\经济政策\\%s\\%s.txt", nowDate, vo.getQuestion());
                String txtContent = "问题：" + vo.getQuestion() + "\n回答:\n" + answer + "\n\n原文：\n" + vo.getContent();
                FileUtil.txtWriter(txtPath, txtContent);
            }


        }
        String excelPath = String.format("C:\\Users\\user\\Desktop\\经济政策\\经济政策文件问题+回答%s.xlsx", nowDate);
        EasyExcel.write(excelPath, TestVO.class)
                .sheet("Sheet1")
                .doWrite(excelList);


    }

    public static void questionAll() {
        List<TestVO> result = new ArrayList<>();
        //1.通用问题+认知问题
        List<TestVO> excelList = readExcelData("C:\\Users\\user\\Desktop\\经济政策\\自我认知+通用问题.xlsx");
        result.addAll(excelList);

        //2.随机问题
        reloadText();
        //每个文件 随机获取两条记录
        for (Map.Entry<String, List<TestVO>> entry : map.entrySet()) {
            List<TestVO> list = entry.getValue();

            Set<Integer> uniqueNumbers = new HashSet<>(); // 使用Set保证不重复
            while (uniqueNumbers.size() < 2) {
                int num = new Random().nextInt(list.size()); // 生成1-100的随机数
                uniqueNumbers.add(num); // 自动去重
            }
            for (Integer uniqueNumber : uniqueNumbers) {
                TestVO vo = list.get(uniqueNumber);
                //生成问题
                Map<String, String> params = new HashMap<>();
                String prompt = "请从以下的内容提炼出一个可以回答的问题： \n\n";
                params.put("question", prompt + vo.getContent());
                String param = JSONObject.toJSONString(params);

                String output = HttpUtils.post("http://192.168.80.51:13999/chat", param);
                String answer = (String) JSONObject.parseObject(output).get("answer");
                vo.setQuestion(answer);
                System.out.println(output);
                System.out.println(answer);


                result.add(vo);
            }
            //System.out.println(entry.getKey() + " " + uniqueNumbers);
            System.out.println("\n");

        }


        //3.excel 导出
        String excelPath = "C:\\Users\\user\\Desktop\\经济政策\\经济政策文件问题.xlsx";
        EasyExcel.write(excelPath, TestVO.class)
                .sheet("Sheet1")
                .doWrite(result);

    }

    public static List<TestVO> readExcelData(String filePath) {
        List<TestVO> result = new ArrayList<>();
        // 创建监听器实例
        TestVOListener listener = new TestVOListener();
        try {
            // 执行读取操作
            EasyExcel.read(new File(filePath))
                    .head(TestVO.class)  // 绑定数据模型类
                    .sheet("Sheet1")    // 指定工作表（默认第一个）
                    .registerReadListener(listener)
                    .doRead();
            result = listener.getDataList();
        } catch (Exception e) {
            System.err.println("读取失败：" + e.getMessage());
            e.printStackTrace();
        }
        return result;
    }


    public static void reloadText() {
        try {
            String fileReadPath = "D:\\ZZZ\\项目文档\\4-经济政策模型\\处理中\\utf-8政务数据集\\福州市\\正文\\福州市政务";
            File rootDirectory = new File(fileReadPath);
            // 存储找到的 .txt 文件的列表
            List<File> txtFiles = new ArrayList<>();
            // 调用递归方法来查找 .txt 文件
            findTxtFiles(rootDirectory, txtFiles);
            int n = 0;
            int m = 0;
            int z = 0;

            // 打印找到的 .txt 文件
            for (File txtFile : txtFiles) {
                //EconomicPolicyContent economicPolicyContent = fileNameAndContent(txtFile.getAbsolutePath());
                fileNameAndContent(txtFile.getPath());


            }

        } catch (Exception e) {
            System.out.println(e.getMessage());

        }
    }

    private static void findTxtFiles(File directory, List<File> txtFiles) {
        // 检查目录是否存在且是一个目录
        if (directory.exists() && directory.isDirectory()) {
            // 获取目录中的所有文件和子目录
            File[] files = directory.listFiles();
            if (files != null) {
                for (File file : files) {
                    // 如果是目录，递归调用
                    if (file.isDirectory()) {
                        findTxtFiles(file, txtFiles);
                    } else {
                        // 如果是文件且扩展名为 .txt，添加到列表中
                        if (file.isFile() && file.getName().endsWith(".txt")) {
                            txtFiles.add(file);
                        }
                    }
                }
            }
        }
    }

    public static void fileNameAndContent(String filePath) throws IOException {
        EconomicPolicyContent economicPolicyContent = new EconomicPolicyContent();
        File file = new File(filePath);
        String fileName = file.getName();
        FileReader reader = new FileReader(filePath);
        BufferedReader bufferedReader = new BufferedReader(reader);
        StringBuilder stringBuilder = new StringBuilder();
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            stringBuilder.append(line).append("\n");
            ;
        }
        bufferedReader.close();
        //log.info(filePath);
        //从文件路径查找年份，window 文件路径：\\  linux:/
        int e = filePath.lastIndexOf("\\");
        String year = filePath.substring(e - 4, e);
        boolean b = year.matches("\\d{4}");

        int k = stringBuilder.toString().length();
        if (k < 500 || k > 10000) {
            return;
        }

        if (b) {
            economicPolicyContent.setYear(Integer.valueOf(year));
            if (economicPolicyContent.getYear() >= 2015) {
                String p1 = filePath.replace("D:\\ZZZ\\项目文档\\4-经济政策模型\\处理中\\utf-8政务数据集\\福州市\\正文\\福州市政务\\", "");
                int n = p1.indexOf("\\");
                String p2 = p1.substring(0, n);
                TestVO vo = new TestVO();
                vo.setQuestion("");
                vo.setType("文件问题");
                vo.setAnswer("");
                vo.setFilePath(p1);
                vo.setFileName(fileName);
                vo.setContent(stringBuilder.toString());
                if (map.containsKey(p2)) {
                    map.get(p2).add(vo);
                } else {
                    List<TestVO> list = new ArrayList<>();
                    list.add(vo);
                    map.put(p2, list);
                }

            }
        }
    }

}

class TestVOListener extends AnalysisEventListener<TestVO> {
    // 存储解析结果的集合
    private final List<TestVO> dataList = new ArrayList<>();

    @Override
    public void invoke(TestVO vo, AnalysisContext context) {
        // 每解析一行数据触发
        dataList.add(vo);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        // 全部解析完成后触发
        System.out.println("共读取 " + dataList.size() + " 条数据");
    }

    // 提供获取结果的接口
    public List<TestVO> getDataList() {
        return dataList;
    }
}


